package com.zzyl.nursing.service.impl;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.FamilyMemberDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.dto.member.DeviceDataListByDayDto;
import com.zzyl.nursing.dto.member.QueryDevicePropertyStatusDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.FamilyMemberElderVo;
import com.zzyl.nursing.vo.FamilyMemberVo;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.nursing.vo.member.DevicePropertiesVo;
import com.zzyl.nursing.vo.member.DevicePropertyStatusVo;
import com.zzyl.nursing.vo.member.HourlyDataVO;
import com.zzyl.nursing.vo.member.PropertyStatusInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-19
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    static List<String> DEFAULT_NICK_NAME = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");

    /**
     * 小程序登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //1.获取openid(调用微信的接口获取) ***
        String openid = wechatService.getOpenid(dto.getCode());

        //2.根据openid查询用户
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId, openid);
        FamilyMember familyMember = getOne(queryWrapper);

        //3.判断用户是否存在，用户不存在，就构建用户
        if (ObjectUtil.isEmpty(familyMember)) {
            /*familyMember = new FamilyMember();
            familyMember.setOpenId(openid);*/
            familyMember = FamilyMember.builder()
                    .openId(openid)
                    .build();
        }

        //4.获取用户的手机号（调用微信的接口获取）***
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //5. 新增或修改用户
        inserOrUpdateFamilyMember(familyMember, phone);

        //6. 把用户的信息封装到token,返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", familyMember.getName());
        claims.put("userId", familyMember.getId());
        String token = tokenService.createToken(claims);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        return loginVo;
    }

    @Autowired
    private IElderService elderService;

    @Autowired
    private IFamilyMemberElderService familyMemberElderService;

    @Override
    public void addFamilyMember(FamilyMemberDto dto) {
        //3.根据身份证查询老人
        Elder elder = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getIdCard())
                .one();
        if (elder.getStatus() == 0 || elder.getStatus() == 5) {
            throw new BaseException("该老人已不在院内");
        }
        if (!dto.getName().equals(elder.getName())) {
            throw new BaseException("姓名不一致");
        }
        //1. 获取成员id
        Long userId = UserThreadLocal.getUserId();
        if (ObjectUtil.isEmpty(userId)) {
            throw new BaseException("请先登录");
        }
        //2.查询到用户
        FamilyMember familyMember = getById(userId);
        if (ObjectUtil.isEmpty(familyMember)) {
            throw new BaseException("用户不存在");
        }
        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        familyMemberElder.setFamilyMemberId(userId);
        familyMemberElder.setElderId(elder.getId());
        familyMemberElder.setRemark(dto.getRemark());

        familyMemberElderService.save(familyMemberElder);
    }

    @Override
    public List<FamilyMemberVo> getMyFamilyMembers() {
        //1. 获取用户id
        Long userId = UserThreadLocal.getUserId();
        if (ObjectUtil.isEmpty(userId)) {
            return null;
        }
        List<FamilyMemberVo> familyMemberVos = familyMemberMapper.selectFamilyMemberById(userId);
        return familyMemberVos;
    }


    @Override
    public List<FamilyMemberElderVo> listByPage() {
        List<FamilyMemberElderVo> vos = familyMemberMapper.listByPage();
        return vos;
    }

    @Autowired
    private IoTDAClient client;

    @Autowired
    private IDeviceDataService deviceDataService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IDeviceService deviceService;

    @Override
    public Map<String, Object> viewHealthData(QueryDevicePropertyStatusDto dto) {

        //1. 查询产品信息
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(dto.getProductKey());
        ShowProductResponse response;
        //2. 获取服务id
        Map<String, Object> vo = new HashMap<>();
        ShowDeviceShadowResponse response1;
        try {
            //调用华为云接口查询产品信息
            response = client.showProduct(request);
            //查询数据库中设备数据 设备名字不能重复 用设备名字获取设备的iotId
            Device device = deviceService.lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).one();
            String iotId = device.getIotId();

            ShowDeviceShadowRequest request1 = new ShowDeviceShadowRequest();
            request1.setDeviceId(iotId);
            response1 = client.showDeviceShadow(request1);
            //获取服务id
            String serviceId = response1.getShadow().get(0).getServiceId();
            //获取服务属性
            List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
            List<Map<String, Object>> propertyStatusInfoVo = queryInfo(serviceCapabilities, serviceId, iotId);
            Map<String, Object> map = new HashMap<>();
            //构造返回数据
            map.put("propertyStatusInfo", propertyStatusInfoVo);
            //构建返回数据
            vo.put("list", map);
        } catch (Exception e) {
            throw new BaseException("查询产品详情失败");
        }
        return vo;
    }

    private List<Map<String, Object>> queryInfo(List<ServiceCapability> serviceCapabilities, String serviceId, String iotId) {
        //属性列表集合
        List<Map<String, Object>> list = new ArrayList<>();
        //通过serviceId过滤出需要的属性
        List<ServiceProperty> properties = serviceCapabilities.stream().filter(serviceCapability -> serviceCapability.getServiceId().equals(serviceId)).findFirst().get().getProperties();
        properties.forEach(p -> {
            //解析获得的属性信息
            Map<String, Object> map = new HashMap<>();
            JSONObject jsonObject = JSONUtil.parseObj(p);
            //将属性添加到map里面
            map.put("identifier", jsonObject.get("propertyName"));
            map.put("dataType", jsonObject.get("dataType"));
            map.put("unit", jsonObject.get("unit"));
            map.put("name", jsonObject.get("description"));
            //添加到集合里面
            list.add(map);
        });
        //从redis中获取设备数据
        Object json = redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, iotId);
        //转成集合,因为存到Redis里面的时候也是集合的形式
        JSONArray jsonArray = JSONUtil.parseArray(json);
        List<DeviceData> deviceData = JSONUtil.toList(jsonArray, DeviceData.class);
        //将这个集合转换成map 其中FunctionId是他的键 value是DeviceData
        Map<String, DeviceData> map = deviceData.stream().collect(Collectors.toMap(DeviceData::getFunctionId, d -> d));
        //将剩余的属性值添加到map里面
        for (Map<String, Object> map1 : list) {
            DeviceData data = map.get(map1.get("identifier"));
            map1.put("value", data.getDataValue());
            LocalDateTime alarmTime = data.getAlarmTime();
            // 定义格式化器（支持你提供的格式）
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX");
            // 定义东八区时区
            ZoneId zoneId = ZoneId.of("Asia/Shanghai");
            // 将 LocalDateTime 转换为 ZonedDateTime
            ZonedDateTime zonedDateTime = alarmTime.atZone(zoneId);
            // 获取时间戳（毫秒）
            long time = zonedDateTime.toInstant().toEpochMilli();
            map1.put("time", time);
        }
        return list;
    }

    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Override
    public List<HourlyDataVO> queryDeviceDataListByDay(DeviceDataListByDayDto dto) {
        Long startTime = dto.getStartTime();
        Long endTime = dto.getEndTime();

        Instant startInstant = Instant.ofEpochMilli(startTime);
        Instant endInstant = Instant.ofEpochMilli(endTime);

        ZoneId zoneId = ZoneId.of("Asia/Shanghai");

        LocalDateTime startLocal = LocalDateTime.ofInstant(startInstant, zoneId);
        LocalDateTime endLocal = LocalDateTime.ofInstant(endInstant, zoneId);

        List<HourlyDataVO> dbResult = deviceDataMapper.selectHourlyData(dto.getIotId(), dto.getFunctionId(), startLocal, endLocal);

        Map<String, Double> resultMap = dbResult.stream()
                .collect(Collectors.toMap(HourlyDataVO::getDateTime, HourlyDataVO::getDataValue));

        List<HourlyDataVO> result = new ArrayList<>();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:00");

        for (LocalDateTime current = startLocal; !current.isAfter(endLocal); current = current.plusHours(1)) {
            String hourKey = current.format(formatter);
            Double value = resultMap.getOrDefault(hourKey, 0.0);
            result.add(new HourlyDataVO(hourKey, value));
        }
        return result;
    }

    @Override
    public List<HourlyDataVO> queryDeviceDataListByWeek(DeviceDataListByDayDto dto) {
        Long startTime = dto.getStartTime();
        Long endTime = dto.getEndTime();

        Instant startInstant = Instant.ofEpochMilli(startTime);
        Instant endInstant = Instant.ofEpochMilli(endTime);

        ZoneId zoneId = ZoneId.of("Asia/Shanghai");

        LocalDateTime startLocal = LocalDateTime.ofInstant(startInstant, zoneId);
        LocalDateTime endLocal = LocalDateTime.ofInstant(endInstant, zoneId);

        List<HourlyDataVO> dbResult = deviceDataMapper.selectDailyData(
                dto.getIotId(), dto.getFunctionId(), startLocal, endLocal);

        Map<String, Double> resultMap = dbResult.stream()
                .collect(Collectors.toMap(HourlyDataVO::getDateTime, HourlyDataVO::getDataValue));

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM.dd");
        List<HourlyDataVO> result = new ArrayList<>();

        for (LocalDateTime current = startLocal; !current.isAfter(endLocal); current = current.plusDays(1)) {
            String dayKey = current.format(formatter);
            Double value = resultMap.getOrDefault(dayKey, 0.0);
            result.add(new HourlyDataVO(dayKey, value));
        }
        return result;
    }

    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    @Override
    public void deleteById(Long id) {
        //删除数据库中的数据
        familyMemberElderMapper.deleteById(id);
    }


    /**
     * 新增或修改用户
     *
     * @param familyMember
     * @param phone
     */
    private void inserOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        //1. 判断新的手机跟数据库中保存的手机号是否一致
        if (ObjectUtil.notEqual(familyMember.getPhone(), phone)) {
            familyMember.setPhone(phone);
        }

        //2. id是否存在，如存在，就修改
        if (ObjectUtil.isNotEmpty(familyMember.getId())) {
            updateById(familyMember);
            return;
        }

        //3. 不存在，就新增 (拼装用户的昵称：随机字符串+手机号后4位)
        int index = (int) (Math.random() * DEFAULT_NICK_NAME.size());
        String nickName = DEFAULT_NICK_NAME.get(index) + phone.substring(phone.length() - 4);
        familyMember.setName(nickName);
        save(familyMember);

    }

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }

}
